/**
 * 
 */
package com.hz.winnie.demands.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hz.winnie.demands.common.DemandsConstants;
import com.hz.winnie.demands.pojo.User;
import com.hz.winnie.demands.service.UserService;
import com.hz.winnie.demands.utils.CookieUtils;

/**
 * @description 用户权限拦截机
 * @author winnie
 * @date 2011-4-16
 * @version 1.0
 */
public class UserAuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    /** 登录连接 */
    private String loginUrl;

    /** 需要登录的controller */
    private List<String> protectControllers;

    @Override
    public boolean preHandle(HttpServletRequest request,
	    HttpServletResponse response, Object handler) throws Exception {
	/** 是否需要登录 */
	if (!protectControllers.contains(handler.getClass().getSimpleName())) {
	    return true;
	}

	if (session.getAttribute(DemandsConstants.SESSION_KEY_USER) != null) {
	    return true;
	}
	String loginWholeUrl = loginUrl + "?toUrl="
		+ getEncodedTargetUrl(request);

	Cookie demIdCookie = CookieUtils.getCookie(request,
		DemandsConstants.COOKIE_KEY_DEM_ID);

	/** cookie存在重新取得user对象放到session中 */
	if (demIdCookie != null
		&& StringUtils.isNotBlank(demIdCookie.getValue())) {
	    User demUser = userService.getUserById(demIdCookie.getValue());
	    session.setAttribute(DemandsConstants.SESSION_KEY_USER, demUser);
	    return true;
	}

	response.sendRedirect(loginWholeUrl);

	return false;
    }

    private String getEncodedTargetUrl(HttpServletRequest request) {
	StringBuffer buff = request.getRequestURL();
	String queryString = request.getQueryString();
	if (queryString != null) {
	    buff.append("?" + queryString);
	}
	try {
	    return URLEncoder.encode(buff.toString(), "UTF-8");
	} catch (UnsupportedEncodingException e) {
	    return buff.toString();
	}
    }

    public String getLoginUrl() {
	return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
	this.loginUrl = loginUrl;
    }

    public List<String> getProtectControllers() {
	return protectControllers;
    }

    public void setProtectControllers(List<String> protectControllers) {
	this.protectControllers = protectControllers;
    }

}
